package com.whh.starter.web.cipher;

import com.alibaba.fastjson.JSON;
import com.whh.starter.cipher.CipherService;
import com.whh.starter.config.RequestContext;
import com.whh.starter.config.annotation.ApiCipherDisable;
import com.whh.starter.config.response.CipherResponse;
import com.whh.starter.properties.CipherProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class EncryptResponseBody implements ResponseBodyAdvice<Object> {

    private static final Logger log = LoggerFactory.getLogger(EncryptResponseBody.class);


    private final CipherService cipherService;
    private final CipherProperties cipherProperties;

    public EncryptResponseBody(CipherService cipherService, CipherProperties cipherProperties) {
        this.cipherService = cipherService;
        this.cipherProperties = cipherProperties;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return cipherProperties.allowResponseCipher() && (!returnType.hasMethodAnnotation(ApiCipherDisable.class) || !returnType.getContainingClass().isAnnotationPresent(ApiCipherDisable.class));

    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        String secretKey = RequestContext.getCurrentContext().getSecretKey();
        if (body == null || body instanceof Resource || secretKey == null) {
            return body;
        }
        try {
            String bodyStr = JSON.toJSONString(body);
            return new CipherResponse(cipherService.symmetricEncrypt(bodyStr, secretKey));
        } catch (Exception e) {
            log.info("加密失败：", e);
        }
        return null;
    }
}
